/*************************************************************************
	> File Name: common.c
	> Author: Maureen 
	> Mail: 1437867946@qq.com 
	> Created Time: Wed 16 Dec 2020 03:34:38 PM CST
 ************************************************************************/

#include "head.h"

char conf_value_ans[512] = {0};

int make_nonblock(int fd) {
    int flag;
    //取出原来的flag
    if ((flag = fcntl(fd, F_GETFL)) < 0) {
        return -1;
    }
    //在原来的flag基础上加个O_NONBLOCK的flag
    flag |= O_NONBLOCK;
    return fcntl(fd, F_SETFL, flag);
}

int make_block(int fd) {
    int flag;
    if ((flag = fcntl(fd, F_GETFL)) < 0) {
        return -1;
    }
    flag &= ~O_NONBLOCK;
    return fcntl(fd, F_SETFL, flag);
} 

char *get_value(const char *path, const char *key) {
    FILE *fp = NULL;
    char *line = NULL, *sub = NULL;
    ssize_t nread, len;
    if (path == NULL || key == NULL) {
        fprintf(stderr, "arg error!\n");
        exit(1);
        //errno = EINVAL; //man errno
        //return NULL;
    }
    if ((fp = fopen(path, "r")) == NULL) {
        fprintf(stderr, "file open error!\n");
        exit(1);
        //return NULL;
    }
    //逐行读取配置文件的内容: man getline()
    while ((nread = getline(&line, &len, fp)) != -1) {
        //字符串中找子串key: strstr 
        if ((sub = strstr(line, key)) == NULL) continue;
        if (line[strlen(key)] == '=' && sub == line) {
            //printf("Find!\n");
            strcpy(conf_value_ans, line + strlen(key) + 1);//从key=后面的值开始取
            conf_value_ans[strlen(conf_value_ans) - 1] = '\0'; 
        }
    }
    //printf("%s = %s\n", key, conf_value_ans);
    free(line);
    fclose(fp);
    return conf_value_ans;
}
